local desc_1v1 = [[
  # 无限火力模式简介

  两人进行对战的竞技化模式，参考国际服

  ___https://gitee.com/RalphR/tenyear

  ## 游戏流程

  1.选将，获得初始buff，开始时体力上限调整为10，随游戏进程会获得各种技能

]]
local pvetool=require "packages/jbs/record/PVETool"

-- FIXME: Disable same convert by param or extra data
local function rm(generals, g)
  local gt = Fk.generals[g].trueName
  for i, v in ipairs(generals) do
    if Fk.generals[v].trueName == gt then
      table.remove(generals, i)
      return
    end
  end
end

--
--技能获得
local function reward_Newskill(room,players)
  local room=room
  local req = Request:new(players, "CustomDialog")
    req.focus_text = "无限火力"
  for _, player in ipairs(players) do
  local existingGenerals = {}
  table.forEach(room.players, function(p)
    table.insertTable(existingGenerals, {p.general, p.deputyGeneral})
  end)
  local generals = table.map(Fk:getGeneralsRandomly(10, Fk:getAllGenerals(), existingGenerals,
    (function(p) return false end)), function(g) return g.name end)
  generals = table.random(generals, math.min(4, #generals))
  local skills = {}
  local choices = {}
for _, general_name in ipairs(generals) do
local general = Fk.generals[general_name]
local g_skills = {}
--加载技能
for _, skill in ipairs(general.skills) do
    table.insertIfNeed(g_skills, skill.name)

end
for _, s_name in ipairs(general.other_skills) do
  local skill = Fk.skills[s_name]

    table.insertIfNeed(g_skills, skill.name)

end
table.insertIfNeed(skills, g_skills)
if #choices == 0 and #g_skills > 0 then
  choices = {g_skills[1]}
end
end

if #choices > 0 then
  
  req:setData(player, {
    path = "packages/tenyear/qml/ChooseGeneralSkillsBox.qml",
    data = {
      generals, skills, 1, 1, "jbsfire__reward",true
    },
  })
  req:setDefaultReply(player,table.random(skills, 1)[1])
end

--结束循环
end


for _, p in ipairs(players) do
  local choice = req:getResult(p)
  room:handleAddLoseSkills(p, choice, nil)
  p:drawCards(1)
end

end

--buff表
local bufflist={"jbsfire_liuanhuaming","jbsfire_mianmianjudao","jbsfire_xushidaifa","jbsfire_duoduoyishan"}

local m_1v1_getLogic = function()
  local m_1v1_logic = GameLogic:subclass("jbsfire_logic")
  --[[
  function m_1v1_logic:prepareDrawPile()
    local room = self.room
    local allCardIds = Fk:getAllCardIds()
    --重新过滤卡组
    local filterCardIds = {}
    local while_cards = {"standard","standard_cards","maneuvering","lang_cards","tenyear_token","mobile_derived","ol_token","overseas_token","jbs_cards"}
    local blacklist = { "amazing_grace"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(while_cards,card.package.name) or table.contains(blacklist, card.name) then
          table.removeOne(allCardIds, id)
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        end
      if table.contains(while_cards,card.package.name) and not table.contains(blacklist, card.name)  then
        if not card.is_derived then
          table.insert(filterCardIds,id)
        end
      end
    end
    end
     
  
  

    local seed = math.random(2 << 32 - 1)
    table.shuffle(filterCardIds,seed)
    room.draw_pile = filterCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)
  end
  --]]
  function m_1v1_logic:chooseGenerals()
    local room = self.room
    local generalNum = room:getSettings('generalNum')
    local n = room:getSettings('enableDeputy') and 2 or 1
    local lord = room:getLord()
    local lord_generals = {}
  
    if lord ~= nil then
      room.current = lord
      room:setBanner("@[:]jbsfire_rule","jbsfire-intro")
      room:setBanner("@jbsfire_assignment","jbsfire-assign1")
      room:setTag("jbsfire_as",3)
      room:setBanner("@jbsfire_assignmentprocess","0 / 3")
      room:setTag("jbsfire_over",false)
    end
  
    local nonlord = room.players
    local generals = room:getNGenerals(#nonlord * generalNum)
    table.shuffle(generals)
    local req = Request:new(nonlord,  "AskForGeneral")
    for i, p in ipairs(nonlord) do
      local buff=table.random(bufflist)
      room:setPlayerMark(p,"@jbsfire_buff",buff)
      local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      req:setData(p, { arg, n })
      req:setDefaultReply(p, table.random(arg, n))

    end

  
    local selected = {}
    for _, p in ipairs(nonlord) do
      local result = req:getResult(p)
      local general, deputy = result[1], result[2]
      table.insertTableIfNeed(selected, result)
      room:findGeneral(general)
      room:findGeneral(deputy)
      room:prepareGeneral(p, general, deputy)
    end
  
    generals = table.filter(generals, function(g) return not table.contains(selected, g) end)
    room:returnToGeneralPile(generals)
    pvetool:configureAI(room)
    room:askForChooseKingdom(nonlord)
  end

  --[[
  function m_1v1_logic:chooseGenerals()
      local room = self.room
      room:setBanner("@jbsfire","jbsfire-intro")
      local generalNum = room:getSettings('generalNum')
      --local n = room:getSettings('enableDeputy') and 2 or 1
      local n=1    
      local nonlord = room.players
      local generals = room:getNGenerals(#nonlord * generalNum)
      table.shuffle(generals)
      for i, p in ipairs(nonlord) do
        local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
        p.request_data = json.encode{ arg, n }
        p.default_reply = table.random(arg, n)
      end
    
      room:notifyMoveFocus(nonlord, "AskForGeneral")
      room:doBroadcastRequest("AskForGeneral", nonlord)
    
      local selected = {}
      for _, p in ipairs(nonlord) do
        if p.general == "" and p.reply_ready then
          local general_ret = json.decode(p.client_reply)
          local general = general_ret[1]
          local deputy = general_ret[2]
          table.insertTableIfNeed(selected, general_ret)
          room:setPlayerGeneral(p, general, true, true)
          room:setDeputyGeneral(p, deputy)
        else
          room:setPlayerGeneral(p, p.default_reply[1], true, true)
          room:setDeputyGeneral(p, p.default_reply[2])
        end
        p.default_reply = ""
      end
    
    
      room:askForChooseKingdom(nonlord)
  end
  --]]

  function m_1v1_logic:broadcastGeneral()--血量置为10血
    local room = self.room
    local players = room.players
  
    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      p.maxHp =10
      p.hp = 10
      p.shield = general.shield 
      room:broadcastProperty(p, "role")     
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
      room:broadcastProperty(p, "deputyGeneral")
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
    end
  end


  return m_1v1_logic
end




local m_1v1_rule = fk.CreateTriggerSkill{
  name = "#jbsfire_rule",
  priority = 0.001,
  refresh_events = {fk.Damage,fk.GameStart},
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local players=room.alive_players
      room:doBroadcastNotify("ShowToast", "无尽火力，无尽痛楚")
      for _, p in ipairs(players) do
        local skill=p:getMark("@jbsfire_buff")
        room:handleAddLoseSkills(p,  "m_bahu", nil, false,true)
        room:handleAddLoseSkills(p,  skill, nil, false,true)
      
      end
      --[[
      room.logic:trigger("fk.Debut", player, player.general, false)
      room.logic:trigger("fk.Debut", player.next, player.general, false)
      if room:getSettings('enableFreeAssign') then---开启自由选将时结束
        room:doBroadcastNotify("ShowToast", "该模式不支持自由选将！")
        --room:gameOver("lord")
        return
      end
      --]]
      --执行奖惩
    elseif event==fk.Damage and not room:getTag("jbsfire_over")==true then
      local assign=room:getTag("jbsfire_as")
      local n=0
      local events = room.logic:getEventsOfScope(GameEvent.Damage,2,function(e)
        local damage = e.data[1]
        if damage and damage.from  then
          n=n+damage.damage
        end
        return false
    end,Player.HistoryGame)
    if assign==8 then n=n-3 end
    room:setBanner("@jbsfire_assignmentprocess",tostring(n).." / "..assign)
    if n>=assign then
      room:doBroadcastNotify("ShowToast", "任务完成，转至下一阶段")
      room:setBanner("@jbsfire_assignment","jbsfire-assign2")
      room:setTag("jbsfire_as",8)
      room:setBanner("@jbsfire_assignmentprocess","0 / 8")
      if assign==8 then
        room:setTag("jbsfire_over",true)
        room:setBanner("@jbsfire_assignment","jbsfire-assignover")
      end
      local players=room.alive_players
      reward_Newskill(room,players)


    end

    end


  end,
}

local liuan = fk.CreateTriggerSkill{
  name = "jbsfire_liuanhuaming",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player.phase == Player.NotActive and player:usedSkillTimes(self.name)<2 then
      for _, move in ipairs(data) do
        if move.from == player.id and (move.to ~= player.id or (move.toArea ~= Card.PlayerHand and move.toArea ~= Card.PlayerEquip)) then
          for _, info in ipairs(move.moveInfo) do
            if (info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip)  then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

local mianmiam = fk.CreateTriggerSkill{
  name = "jbsfire_mianmianjudao",
  frequency = Skill.Compulsory,
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self.name) then return false end
    return  target==player and target.phase == Player.Start
  end,
 
  on_use = function(self, event, target, player, data)
    local room = player.room
    local s={"trick","basic"}
    for i=1,2 do
    local cards = room:getCardsFromPileByRule(".|.|.|.|.|"..s[i],1)
      if #cards > 0 then
          room:obtainCard(player, cards[1], true, fk.ReasonJustMove)
      end
    end
  end,
}

local duoduoyishan = fk.CreateTriggerSkill{
  name = "jbsfire_duoduoyishan",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

local xushidaifa = fk.CreateTriggerSkill{
  name = "jbsfire_xushidaifa",
  frequency = Skill.Compulsory,
  events = {fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark(self.name.."-turn") == 0 and data.card
    and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage +1
    player.room:addPlayerMark(player,self.name.."-turn",1)
   
  end,
}


Fk:addSkill(liuan)
Fk:addSkill(mianmiam)
Fk:addSkill(duoduoyishan)
Fk:addSkill(xushidaifa )

Fk:loadTranslationTable{
  ["jbsfire_liuanhuaming"]="柳暗花明",
  [":jbsfire_liuanhuaming"]="每回合限2次，你于回合外失去牌时，摸一张牌",
  ["jbsfire_mianmianjudao"]="面面俱到",
  ["jbsfire_duoduoyishan"]="多多益善",
  [":jbsfire_duoduoyishan"]="每回合结束，摸1张牌",
  ["jbsfire_xushidaifa"]="蓄势待发",
  [":jbsfire_xushidaifa"]="每回合杀造成的第1次伤害+1。",
  [":jbsfire_mianmianjudao"]="准备阶段，从牌堆里获得基本，锦囊牌各一张",


}




local m_1v1_mode = fk.CreateGameMode{
  name = "jbsfire_mode",
  minPlayer = 2,
  maxPlayer = 2,
  rule ="#jbsfire_rule",
  logic = m_1v1_getLogic,
  surrender_func = function(self, playedTime)
    return { { text = "time limitation: 2 min", passed = playedTime >= 120 } }
  end,
}
-- extension:addGameMode(m_1v1_mode)
Fk:loadTranslationTable{
  ["jbsfire_mode"] = "无限火力gbs",
  [":jbsfire_mode"] = desc_1v1,
  ["@jbsfire_buff"]="",
  ["@jbsfire_assignment"]="任务",
  ["@[:]jbsfire_rule"]="模式",
  ["jbsfire-intro"]="无限火力",
  [":jbsfire-intro"]=[[该模式下双方都有十滴血，每
  局游戏都会给两名玩家提供两个恒定Buff(固定跋扈+随机奖励)。每局游戏限两次，当全场造成伤害量达到定值时，两名玩家各获得一个新技能
  <br>奖励一览：<br>柳暗花明：每回合限2次，你于回合外失去牌时，摸一张牌
  <br>面面俱到:准备阶段，从牌堆里获得基本，锦囊牌各一张
  <br>多多益善:每回合结束，摸1张牌
  <br>蓄势待发:每回合杀造成的第1次伤害+1。]],
  ["@jbsfire_assignmentprocess"]="任务进度",
  ["jbsfire-assign1"]="全场累计造成3点伤害",
  ["jbsfire-assign2"]="全场累计造成8点伤害",
  ["jbsfire-assignover"]="所有任务已完成",
  ["jbsfire__reward"]="选择一个武将技能并获得",
}

return m_1v1_mode
